import { login } from "../../api/user";
import { getToken, setToken, removeToken, getTenantKey, setTenantKey, removeTenantKey,setTID,getTID } from '@/utils/auth'
import {getUser, setUser} from "../../utils/localStorageData";
import {getInfo} from "../../api/user";

const state = {
  token: getToken(),
  uid: '',
  tid: getTID(),
  TenantKey: getTenantKey(),
  userInfo: getUser()
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_TENANT_KEY: (state, token) => {
    state.TenantKey = token
  },
  SET_TID: (state, token) => {
    state.TenantKey = token
  },
  SET_USER_INFO: (state, info) => {
    state.userInfo = info
    state.uid = info.id;
    setUser(info)
  }
}

const actions = {
  // 登录
  login({ commit }, loginInfo) {
    return new Promise((resolve, reject) => {
      login(loginInfo)
        .then(res => {
          if (res.code == 200 || res.code == 5100 || res.code == 5200 || res.code == 5300 || res.code == 410) {
            if (res.data.user){
              let token = res.data.token
              let key = res.data.user.tenant_key
              let tid = res.data.user.hospital_id;
              commit('SET_TOKEN', token)
              commit('SET_TENANT_KEY', key)
              commit('SET_TID', tid)
              // commit('SET_USER_INFO', res.data.user)
              setToken(token)
              setTenantKey(key)
              setTID(tid);
              if (res.code == 200){
                resolve(res.code)
              }else {
                resolve(res.code)
              }
            }else {
              reject("user is null")
            }

          } else {
            reject(res.msg)
          }
          // const { token } = res.entry
          // commit('SET_TOKEN', token)
          // setToken(token)

        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // // 登出
  // logout({ commit, state }) {
  //   return new Promise((resolve, reject) => {
  //     commit('SET_TOKEN', '')
  //     removeToken()
  //     resolve()
  //   })
  // },

  // 获取基本用户信息
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo().then(res => {
          if (res.code == 200){
            commit('SET_USER_INFO', res.data)
            resolve(res.data)
          }else {
            reject(res.msg);
          }

        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // // 重置token
  // resetToken({ commit }) {
  //   return new Promise(resolve => {
  //     commit('SET_TOKEN', '')
  //     removeToken()
  //     resolve()
  //   })
  // }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
